// 原始曲线数据
const P0 = { x: 360, y: 200 };
const P1 = { x: 300, y: 210 };
const P2 = { x: 240, y: 150 };
const P3 = { x: 230, y: 20 };

// 计算曲率
function computeCurvature(P0, P1, P2, P3, t) {
    // 贝塞尔曲线导数
    const B_prime = t === 0 
        ? { x: 3 * (P1.x - P0.x), y: 3 * (P1.y - P0.y) }  // B'(0)
        : { x: 3 * (P3.x - P2.x), y: 3 * (P3.y - P2.y) }; // B'(1)

    const B_double_prime = t === 0 
        ? { x: 6 * (P0.x - 2 * P1.x + P2.x), y: 6 * (P0.y - 2 * P1.y + P2.y) }  // B''(0)
        : { x: 6 * (P1.x - 2 * P2.x + P3.x), y: 6 * (P1.y - 2 * P2.y + P3.y) }; // B''(1)

    // 叉积 |B' × B''|
    const cross = B_prime.x * B_double_prime.y - B_prime.y * B_double_prime.x;
    // 模长 |B'|^3
    const B_prime_mag = Math.sqrt(B_prime.x ** 2 + B_prime.y ** 2);

    return Math.abs(cross) / (B_prime_mag ** 3);
}

// 原始曲率
const k0 = computeCurvature(P0, P1, P2, P3, 0);
const k1 = computeCurvature(P0, P1, P2, P3, 1);
console.log('k0',k0)
console.log('k1',k1)

// 新起点和终点
// const P0_new = { x: 400, y: 300 };
// const P3_new = { x: 300, y: 100 };

// 优化目标：调整 P1_new 和 P2_new，使曲率匹配 k0 和 k1
function findNewControlPoints(P0_new, P3_new, k0, k1) {
    // 初始猜测（按比例缩放）
    const scale = Math.sqrt(
        ((P3_new.x - P0_new.x) ** 2 + (P3_new.y - P0_new.y) ** 2) /
        ((P3.x - P0.x) ** 2 + (P3.y - P0.y) ** 2)
    );

    let P1_new = {
        x: P0_new.x + (P1.x - P0.x) * scale,
        y: P0_new.y + (P1.y - P0.y) * scale
    };

    let P2_new = {
        x: P0_new.x + (P2.x - P0.x) * scale,
        y: P0_new.y + (P2.y - P0.y) * scale
    };

    // 牛顿迭代优化（简化版，仅迭代几次）
    const learningRate = 0.1;
    const maxIterations = 100;
    const tolerance = 1e-6;

    for (let i = 0; i < maxIterations; i++) {
        // 计算当前曲率
        const current_k0 = computeCurvature(P0_new, P1_new, P2_new, P3_new, 0);
        const current_k1 = computeCurvature(P0_new, P1_new, P2_new, P3_new, 1);

        // 计算误差
        const error0 = current_k0 - k0;
        const error1 = current_k1 - k1;
        const totalError = error0 ** 2 + error1 ** 2;

        if (totalError < tolerance) break;

        // 调整 P1_new 和 P2_new（简化梯度下降）
        P1_new.x -= learningRate * error0;
        P1_new.y -= learningRate * error0;
        P2_new.x -= learningRate * error1;
        P2_new.y -= learningRate * error1;
    }

    return { c1:P1_new, c2:P2_new };
}

// const { P1_new, P2_new } = findNewControlPoints(P0_new, P3_new, k0, k1);

// console.log("优化后的控制点1:", P1_new);
// console.log("优化后的控制点2:", P2_new);